# 把测试脚本结构优化，脚本参数化以及测试报告所有的技术合并
import csv

import requests


class WorkFlowNewTestV3:
    def user_interface_test(self, url, user_info, exp_result, name):
        # 定义字典数据，存储实际接口响应结果和测试结论
        result_data = {}
        # 发送请求
        res = requests.post(url, data=user_info).text
        print(res)
        result_data["接口返回值"] = res
        r = res.find(exp_result)
        if r > 0:
            print(name + "测试通过")
            result_data["测试结论"] = "测试通过"
        else:
            print(name + "测试不通过")
            result_data["测试结论"] = "测试不通过"
        return result_data

    # 把相关的测试结论写入测试报告
    def result_report(self, name, report_name, res):
        file = open(report_name, "a")
        for k, v in res.items():
            file.write(f"{name},{k},{v}")
        file.write("\n")
        file.close()


if __name__ == '__main__':
    obj = WorkFlowNewTestV3()
    file = open("../data/interface_datas.csv", "r")
    tables = csv.reader(file)
    user_info = {}
    report_name = "../data/testresult2.csv"
    for row in tables:
        url = row[1]
        exp_result = row[3]
        name = row[5]
        j = int(row[6])
        for i in range(7, 2 * j + 7, 2):
            user_info[row[i]] = row[i + 1]
        # 调用接口测试方法，传入接口测试数据
        res = obj.user_interface_test(url, user_info, exp_result, name)
        user_info = {}
        obj.result_report(name, report_name, res)
